package com.maxcion.scalelayoutmanager.adapter

import android.content.Context
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView


class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val mContentView: View
    private val mViews: SparseArray<View?>
    fun <T : View?> getView(viewId: Int): T? {
        var view: View? = mViews[viewId]
        if (view == null) {
            view = mContentView.findViewById(viewId)
            mViews.put(viewId, view)
        }
        return view as T
    }

    fun setGone(viewId: Int, gone: Boolean): BaseViewHolder {
        val apply = getView<View>(viewId)?.apply {
            visibility = if (gone) View.GONE else View.VISIBLE
        }

        return this
    }

    fun setText(viewId: Int, content: String?): BaseViewHolder {
        val textView: TextView = getView(viewId)!!
        textView.text = content
        return this
    }

    fun setImageResource(viewId: Int, imageResId: Int): BaseViewHolder {
        val view = getView<ImageView>(viewId)
        view?.setImageResource(imageResId)
        return this
    }

    fun setItemClickListener(listener: View.OnClickListener?) {
        mContentView.setOnClickListener(listener)
    }

    fun setViewClickListener(viewId: Int, clickListener: View.OnClickListener?) {
        getView<View>(viewId)?.setOnClickListener(clickListener)
    }

    companion object {
        fun getHolder(context: Context, parent: ViewGroup?, layoutId: Int): BaseViewHolder {
            val itemView: View = LayoutInflater.from(context).inflate(layoutId, parent, false)
            return BaseViewHolder(itemView)
        }
    }

    init {
        mContentView = itemView
        mViews = SparseArray<View?>()
    }
}